#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "sens_receiver.h"

/* The function that is called for each received
 * packet of sensor data.
 */
int callback(tsens_data sens_data) {
  show_sens_data(sens_data); /* just show it on stdout */
  printf("\n");
  return 0;
}

/* for the threading version */
void ctrlc(int sig) {
  printf("caught SIGINT, stop_receiving\n");  
  stop_receiving(SENS_PORT);
  printf("receiving stopped\n");
}

/* Accepting n (first argument) sensor packets
 * and displaying them on stdout. 
 * On 0 (default) it runs as separate thread until interrupted by CTRL-C
 */
int main(int argc, char *argv[]) {
  int no_packets = 0;

  printf("%s n    n=0 receive until interrupted, n packets otherwise\n", argv[0]);
  if (argc == 2)
    no_packets = atoi(argv[1]);
  /* open the connection and registers callback */
  if (sens_open(SENS_PORT, callback) != 0) { 
    printf("opening sensor failed");
    return -1;
  }
  if (no_packets > 0) {
    printf("Getting %d packets\n", no_packets);
    /* expect no packets without timeout */
    while (no_packets-- > 0) {
      printf("%4d: ", no_packets);
      /* receives one package and calls callback */
      receive_one(SENS_PORT); 
    }
  } else {
    printf("processing packets in thread, Ctrl-C to stop\n");
    /* receiving in separate thread with timeout */
    signal(SIGINT, ctrlc);  /* stop receiving on Ctrl-C */
    start_receiving(SENS_PORT);
    while (is_receiving(SENS_PORT)) {
      sleep(1);
    }
  }
  return 0;
}
